package cn.just.utils;

import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author wujiaming
 */
public class THUtils {
    private static TemplateEngine te = null;
    static{
        //创建模板引擎对象
        te = new TemplateEngine();
        //创建解析器对象
        ClassLoaderTemplateResolver r = new ClassLoaderTemplateResolver();
        //设置字符集
        r.setCharacterEncoding("UTF-8");
        //设置后缀
        r.setSuffix(".html");
        //引擎和解析器关联
        te.setTemplateResolver(r);
    }

    /**
     * 通过模板引擎把页面和容器里面的数据合并在一起 返回值是 替换后得到新的html
     * @param path
     * @param context
     * @param response
     * @throws IOException
     */
    public static void write(String path, Context context, HttpServletResponse response)
            throws IOException {
        String html = te.process(path,context);
        //把html返回到浏览器
        response.setContentType("text/html;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.print(html);
        pw.close();
    }
}
